<template>
  <div class="add-collection-plan">
    <el-card class="container-card">
      <template #header>
        <el-row class="container-card-header">
          <el-col :span="6">
            <div class="container-card-header__item">申请人：<span>{{ $store.getters.nickName }}</span></div>
          </el-col>
          <el-col :span="6">
            <div class="container-card-header__item">申请人部门：<span>{{ $store.getters.deptName }}</span></div>
          </el-col>
          <el-col :span="6">
            <div class="container-card-header__item">
              申请日期：<span>{{ today }}</span>
              <i class="el-icon-date"></i>
            </div>
          </el-col>
        </el-row>
      </template>
      <!--      卡片内容-->
      <div class="container-card-body">
        <!--        回款基本信息表单-->
        <el-form class="basic-form" ref="basicForm" :model="payColSchApp" :rules="payColSchAppRules"
                 label-width="130px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="回款类型：" prop="collectionType">
                <el-radio-group v-model="payColSchApp.collectionType">
                  <el-radio :label="1">合同回款</el-radio>
                  <el-radio :label="2">保证金回款</el-radio>
                  <el-radio :label="3">其他回款</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="关联项目：" prop="projectName">
                <el-select v-model="payColSchApp.projectName" @change="onProjectSelectChange">
                  <el-option v-for="item in projectMap" :value="item.projectName" :label="item.projectName"
                             :key="item.projectId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称：" prop="projectCustomer">
                <el-input v-model="payColSchApp.projectCustomer" readonly data-readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="basic-form-tips">选择关联项目后自动填充客户名称，无需手动输入</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户经理：" prop="customerManager">
                <el-input v-model.trim="payColSchApp.customerManager" placeholder="请输入" maxlength="30"
                          clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="basic-form-tips">默认项目指定客户经理，支持修改，此处客户经理负责回款事宜跟进</div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请标题：" prop="applicationTitle">
                <el-input v-model.trim="payColSchApp.applicationTitle" placeholder="请输入" maxlength="30"
                          show-word-limit
                          clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="应收金额(元)：" prop="amountReceivable">
                <el-input v-model.trim="payColSchApp.amountReceivable" placeholder="请输入" maxlength="30"
                          clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="备注：" prop="remarks">
                <el-input v-model="payColSchApp.remarks" placeholder="请输入" type="textarea" :rows="3" resize="none"
                          maxlength="100" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="回款方式：" :rules="{required:true}">
                <el-radio-group :value="collectionMethod" @input="handleChangeCollectionMethod">
                  <el-radio :label="0">自定义</el-radio>
                  <el-radio :label="1">月度</el-radio>
                  <el-radio :label="2">季度</el-radio>
                  <el-radio :label="3">年度</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!--        回款方式表单-->
          <el-row :gutter="20">
            <el-col :span="24">
              <div style="margin-left: 130px">
                <collection-type class="collection-type" ref="collectionType" :method="collectionMethod"
                                 :main="payColSchApp"/>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <div class="footer-btn">
      <el-button @click="handleGoBack">返回</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="btnIsLoading">提交</el-button>
    </div>
  </div>
</template>

<script>
import dayjs from '@/plugins/dayjs'
import CollectionType from './components/CollectionType.vue'
import {projectMap} from './mocks/index'
import {cloneDeep} from 'lodash'
import {aipAddCollectionPlan, apiGetCollectionInfo} from "@/api/process-control-platform/sale/collectionPlan";

// 回款基本信息原始对象
const originPayColSchApp = {
  amountReceivable: null,     // 应收金额
  applicant: '',              // 申请人昵称
  applicantId: '',            // 申请人id
  applicantDept: '',          // 申请人部门
  applicationDate: '',        // 申请日期
  applicationTitle: '',       // 申请标题
  collectionType: 1,          // 回款类型（1-合同回款 2-保证金回款 3-其他回款 4-项目决算）
  customerManager: '',        // 客户经理
  projectCustomer: '',        // 客户名称
  projectId: null,            // 关联项目id
  projectName: '',            // 关联项目
  remarks: '',                // 备注
}

export default {
  name: "addCollectionPlan",
  components: {CollectionType},
  provide() {
    return {
      vm: this,
      planInfo: this.planInfo
    }
  },
  data() {
    return {
      projectMap, // 项目相关假数据

      // 今日的 年月日 信息
      today: dayjs().format('YYYY-MM-DD'),
      // 回款基本信息
      payColSchApp: Object.assign({}, originPayColSchApp),
      // 回款基本信息验证规则
      payColSchAppRules: {
        collectionType: {required: true},
        projectName: {required: true, message: '请选择关联项目', trigger: 'change'},
        customerManager: {required: true, message: '请输入客户经理', trigger: 'change'},
        applicationTitle: {required: true, message: '请输入申请标题', trigger: 'change'},
        amountReceivable: [
          {required: true, message: '请输入应收金额', trigger: 'change'},
          {
            pattern: /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0){1}$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/,
            message: '请输入正确的金额',
            trigger: 'change'
          }
        ]
      },
      // 回款方式
      collectionMethod: 0,
      btnIsLoading: false,

      // 修改模式下子组件需回显的值
      planInfo: {}
    }
  },
  created() {
    // 如果是
    if(this.$route.query.id){
      this.getInfo()
    }
  },
  methods: {
    // 回款方式变化的回调
    handleChangeCollectionMethod(label) {
      this.$confirm('切换回款方式将不保留当前填写内容，是否确定切换?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.collectionMethod = label
      })
    },

    // 关联项目选择器变化时的回调
    onProjectSelectChange(value) {
      // TODO 项目管理做好后，需要根据具体的字段名称修改此处的赋值
      const {projectId, projectCustomer, customerManager} = this.projectMap.find(i => i.projectName === value)
      this.payColSchApp.projectId = projectId
      this.payColSchApp.projectCustomer = projectCustomer
      this.payColSchApp.customerManager = customerManager
      // this.$forceUpdate()
    },

    // 点击返回按钮的回调
    handleGoBack() {
      this.$router.go(-1)
    },

    // 点击提交按钮的回调
    handleSubmit() {
      // 对本组件、子组件、孙子组件分别进行表单验证
      const self = this.validateForm()
      const descendant = this.$refs.collectionType.validateForm()
      Promise.all([self, ...descendant]).then(res => {
        const req = {
          payColMethodDto: res[1],
          payColSchAppDto: res[0],
          payColSchInfoDtoList: res[2],
        }
        // 调用新增回款计划的接口
        aipAddCollectionPlan(req).then(res => {
          if (res.code === 200) {
            this.$message.success('新增回款计划成功')
            this.$router.go(-1)
          }
        }).finally(() => {
          this.btnIsLoading = false
        })
      }).catch(err => {
        console.error(err)
      })
    },

    // 表单验证，返回处理后的值
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs.basicForm.validate((valid) => {
          if (valid) {
            this.payColSchApp.applicant = this.$store.getters.nickName
            this.payColSchApp.applicantDept = this.$store.getters.deptName
            this.payColSchApp.applicantId = this.$store.getters.userId
            this.payColSchApp.applicationDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
            const copyObj = cloneDeep(this.payColSchApp)
            resolve(copyObj)
          } else {
            reject()
          }
        })
      })
    },

    /*---------------详情回显值处理-------------------------*/
    getInfo() {
      apiGetCollectionInfo(this.$route.query.id).then(res => {
        if (res.code !== 200) return
        this.planInfo = res.data
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-collection-plan {
  padding: 20px;

  .container-card {
    &-header {
      margin-left: 60px;
      font-size: 16px;
      font-weight: 500;

      &__item {
        span {
          font-family: "PingFang SC Bold";
          font-weight: 700;
          font-size: 16px;
          line-height: 24px;
          color: #000000d9;
        }

        i {
          margin-left: 30px;
          color: #cccccc;
        }
      }
    }

    &-body {
      .basic-form {
        &-tips {
          line-height: 36px;
        }

        ::v-deep {
          .el-form-item {
            .el-form-item__label {
              flex-shrink: 0;
            }

            .el-form-item__content {
              margin-left: 0;
              flex: 1;
            }

            .el-date-editor {
              width: 100%;
            }

            .el-input-number {
              width: 100%;

              .el-input__inner {
                text-align: left;
              }
            }

            .el-cascader {
              width: 100%;
            }

            .el-select {
              width: 100%;
            }
          }
        }
      }

      ::v-deep {
        .el-input__inner[data-readonly] {
          background: #f1f1f1;
        }
      }
    }
  }

  .footer-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 40px;
    margin-top: 65px;
  }
}
</style>
